/**
 * 
 */
package com.service.tag;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.pub.exception.InitializeException;
import com.pub.i.AttributesI;
import com.pub.i.SourceI;
import com.pub.pub.ConfigureFile;
import com.service.api.google.GetKeywordStats;
import com.service.api.google.GoogleServices;
import com.service.i.ConfigureServiceTagI;
import com.service.merchant.domain.Merchant;
import com.service.merchant.domain.MerchantAttribute;
import com.service.merchant.impl.MerchantImpl;
import com.service.merchant.key.MerchantKey;
import com.service.vo.KeywordVo;

/**
 * @author iling
 *
 */
public class GetMerchantAttributes 
{
	private static Logger logger ;
	
	private String DBTag;
	
	private String email, password, userAgent, developerToken;
	
	private ConfigureFile configureFile;
	
	private MerchantImpl merImpl;
	private GoogleServices googleService;
	
	static
	{
		logger 	= Logger.getLogger(GetMerchantAttributes.class.getName());
	}

	/**
	 * 
	 */
	public GetMerchantAttributes() 
	{
		
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		GetMerchantAttributes service = new GetMerchantAttributes();

		service.handle(args);
	}

	public void init(String[] args) throws InitializeException
	{
		configureFile 	= new ConfigureFile();
		
		try {
			configureFile.initLog4j();
			configureFile.loadPropertyFile(GetMerchantAttributes.class.getSimpleName());
			configureFile.loadPropertyFile("google");
			
			DBTag 			= configureFile.getValueStringNotNull(ConfigureServiceTagI.DB_TAG_HOHO);

			email 			= configureFile.getValueStringNotNull(ConfigureServiceTagI.ACCOUNT_EMAIL);
			password		= configureFile.getValueStringNotNull(ConfigureServiceTagI.ACCOUNT_PASSWORD);
			userAgent		= configureFile.getValueStringNotNull(ConfigureServiceTagI.ACCOUNT_USER_AGENT);
			developerToken	= configureFile.getValueStringNotNull(ConfigureServiceTagI.ACCOUNT_DEVELOPERTOKEN);


			logger.info("email : 		" + email);
			logger.info("userAgent : 	" + userAgent);
			logger.info("developerToken : 	" + developerToken);
			
			logger.info("DB tag : " + DBTag);
			
			
			merImpl			= new MerchantImpl(DBTag);
			googleService 	= new GoogleServices(email, password, userAgent, developerToken);
		} catch (Exception e) {
			e.printStackTrace();
			throw new InitializeException("Initialize failure.", e);
		}
		
	}
	
	public void handle(String[] args)
	{
		try{
			init(args);
// max count: 760
			List<Merchant> mers = merImpl.getCustom(" WHERE id NOT IN (SELECT merchantId FROM log_merchantRequestGoogle) LIMIT 760");
			
			System.out.println("merchant count : " + mers.size());
			
			GetKeywordStats getStats = googleService.getKeywordStatsService();
			
			KeywordVo vo;
			MerchantKey key;
			MerchantAttribute attri;
			
			Map<String, KeywordVo> keywords = new HashMap<String, KeywordVo>(mers.size());
			
			// set request keyword list
			for(Merchant mer: mers){
				vo = new KeywordVo();
				
				vo.setKeyword(mer.getName());
				
				keywords.put(mer.getName().toLowerCase(), vo);
			}
			
			// set google keyword attributes			
			Long globalMonthlySearches;
	    	Long averageMonthlySearches;
	    	
	    	Double competition;
	    	
	    	System.out.println("request google attributes... ");
	    	getStats.getStats(keywords, 0, keywords.size());
	    	
	    	System.out.println("fetch google attributes.");
			for(Merchant mer: mers){
				vo = keywords.get(mer.getName().toLowerCase());
				
				if(vo != null){
					globalMonthlySearches 	= 0L;
					averageMonthlySearches	= 0L;
					competition				= 0D;
					
					
					if(vo.containsKey(AttributesI.COMPETITION)){
						competition = (Double)vo.get(AttributesI.COMPETITION);
						
						key = new MerchantKey();
						
						key.setSourceId(SourceI.SOURCE_GOOGLE);
						key.setMerchantId(mer.getId());
						key.setAttributeId(51);
						
						attri = new MerchantAttribute();
						
						attri.setAttributeValue(competition.toString());
						attri.setPrimaryKey(key);
						
						mer.putAttribute(key, attri);
					}
					
					if(vo.containsKey(AttributesI.GLOBAL_MONTHLY_SEARCHES)){
						globalMonthlySearches = (Long)vo.get(AttributesI.GLOBAL_MONTHLY_SEARCHES);
						
						key = new MerchantKey();
						
						key.setSourceId(SourceI.SOURCE_GOOGLE);
						key.setMerchantId(mer.getId());
						key.setAttributeId(52);
						
						attri = new MerchantAttribute();
						
						attri.setAttributeValue(globalMonthlySearches.toString());
						attri.setPrimaryKey(key);
						
						mer.putAttribute(key, attri);
					}
					
					if(vo.containsKey(AttributesI.AVERAGE_MONTHLY_SEARCHES)){
						averageMonthlySearches = (Long)vo.get(AttributesI.AVERAGE_MONTHLY_SEARCHES);
						
						key = new MerchantKey();
						
						key.setSourceId(SourceI.SOURCE_GOOGLE);
						key.setMerchantId(mer.getId());
						key.setAttributeId(53);
						
						attri = new MerchantAttribute();
						
						attri.setAttributeValue(averageMonthlySearches.toString());
						attri.setPrimaryKey(key);
						
						mer.putAttribute(key, attri);
					}
				}			
				
			}
			
			System.out.println("start write merchnat attributes...");
			
			List<String> columns = new ArrayList<String>();
			columns.add("sourceId");
			columns.add("merchantId");
			columns.add("attributeId");
			columns.add("attributeValue");
			
			List<String> row;
			List<List<String>> rows = new ArrayList<List<String>>();
			for(Merchant mer: mers){
				for(Entry<MerchantKey, MerchantAttribute> entry: mer.getAttributes().entrySet()){
					row = new ArrayList<String>();
					
					row.add(Integer.toString(entry.getKey().getSourceId()));
					row.add(Integer.toString(entry.getKey().getMerchantId()));
					row.add(Integer.toString(entry.getKey().getAttributeId()));
					
					row.add(entry.getValue().getAttributeValue());
					
					rows.add(row);
				}
			}
			
			
//			DBUtils dbutil = new DBUtils();
//			
//			dbutil.insert(DBTag, "merchant_attributes", columns, rows);
//			
//			
//			//write tag attributes to tag_attributes table of DB.
////			merImpl.insertAttributes(mers);
//
//			System.out.println("start write merchnat log...");
//			
//			columns.clear();
//			rows.clear();
//			
//			
//			columns.add("searchCount");
//			columns.add("merchantId");
//			columns.add("status");
//			
//			
//			for(Merchant mer: mers){				
//				for(Entry<MerchantKey, MerchantAttribute> entry: mer.getAttributes().entrySet()){
//					row = new ArrayList<String>();
//					
//					row.add("1");
//					row.add(Integer.toString(entry.getKey().getMerchantId()));
//					row.add(Integer.toString(StatusI.NORMAL));
//					
//					rows.add(row);
//				}
//			}
//			
//			int updateCount = dbutil.insert(DBTag, "log_merchantRequestGoogle", columns, rows);
//			System.out.println("=====================update log count = " + updateCount);
////			LogMerchantRequestGoogle taglog;
////			for(Merchant tag: mers){
////				taglog = new LogMerchantRequestGoogle();
////				
////				taglog.setMerchantId(tag.getId());
////				taglog.setSearchCount(1);
////				taglog.setStatus(StatusI.NORMAL);
////				
////				merImpl.insertRequestGoogleLog(taglog);
////			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
